package com.my.study.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 编写简单的缓存
 *
 * 模仿读写:读写必须分离
 *          读读可以共存
 */
public class MyCache {

    private volatile Map<String,Object> map = new HashMap<>();

    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    /**
     * 数据写入
     *
     * @param key
     * @param value
     */
    public void put(String key,Object value){
        lock.writeLock().lock();
        try{
            System.out.println("数据正在写入:"+key);
            TimeUnit.MICROSECONDS.sleep(300);
            map.put(key,value);
            System.out.println("数据写入成功");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.writeLock().unlock();
        }
    }

    /**
     * 读取数据
     *
     * @param key
     */
    public void get(String key){
        lock.readLock().lock();
        try{
            System.out.println("数据正在读取:"+key);
            map.get(key);
            System.out.println("数据读取成功");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.readLock().unlock();
        }
    }

    /**
     * 清空缓存
     *
     * @return
     */
    public String clearCache(){
        map.clear();
        return "success";
    }
}
